package petrus.mood.grid 
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.display.ContentDisplay;
	import com.greensock.loading.ImageLoader;
	import com.greensock.loading.LoaderMax;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.system.ImageDecodingPolicy;
	import flash.system.LoaderContext;
	import petrus.components.scroll.AbstractScrollBar;
	import petrus.mood.grid.config.Column;
	import petrus.mood.grid.config.Size;
	import petrus.mood.items.photo.PhotoItem;
	
	/**
	 * ...
	 * @author Benoit Petrus
	 */
	public class Board extends Sprite 
	{
		static private const HEIGTH:Number = 250;
		
		private var index 		: int = 0;
		private var queue		:LoaderMax;
		private var TOTAL_TO_LOAD	:int = 0;
		private var TOTAL_LOADED	:int = 0;
		private var TOTAL_ITEM	:int = 0;
		private var IS_LOADING	:Boolean = false;
		private var items		:Array;
		private var destY		:Number;
		private var _scroll		:AbstractScrollBar;
		private var canvas		:BitmapData;
	
		private var zp:Point;
		private var imgW:Number;
		private var imgH:Number;
		
		public var max_posy:Number = 1;
		public var percent : Number = 0;
		
		
		public function Board() 
		{
			zp = new Point();
			createQueue()
			items  	= [];		
		}
		
		public function build(data:XML):void 
		{
			var len 	: Number 	= data.posts.post.length();
			var posX 	: int 		= 0 ;			
			TOTAL_LOADED = 0
				

			for (var i:int = 0; i <  len; i++) 
			{				
				if (data.posts.post[i].@type == "photo")
				{
					TOTAL_ITEM++
					TOTAL_TO_LOAD++
					var item:PhotoItem = new PhotoItem();
						item.setData(data.posts.post[i]);
						item.name = "item" + TOTAL_ITEM;
						//item.visible = false
					addChild(item)
					items.push(item);	
				}
			}			
			
			
			setPositions()
			loadItems()		
			
			imgW  = 824
			imgH  = 549
			canvas = new BitmapData(imgW, imgH, false);
			addChildAt(new Bitmap(canvas) , 0);
		}
		
		public function onMouseWheel(p_delta : Number):void
		{
			var nextPos: Number = this.y  +  p_delta * 40
			if (nextPos > 0 ) 	nextPos = 0
			if (nextPos < -max_posy ) 	nextPos = -max_posy
		
			percent =  -nextPos / max_posy;
			updatePos(percent)
		}
		
		
		
		public function updatePos(percent:Number):Boolean 
		{
			this.y  = - percent * max_posy
			percent =  -this.y / max_posy;	
			
			/*
			// CHECK VISIBILITY
			var i:int = 0;
			while (i<TOTAL_ITEM) 
			{
				var item : PhotoItem = items[i] as PhotoItem;
				// ITEM DU HAUT , ITEMS DU BAS
				if (item.y + this.y >= -50 && ( item.y + this.y ) <=  stage.stageHeight - 50  )item.visible = true
				else item.visible = false
				i++
			}	*/
			
			if (this.y <  -max_posy + 900)
			{
				trace("[Board.updatePos] CHECK POS VALID "+TOTAL_TO_LOAD , TOTAL_ITEM , IS_LOADING);
				if (TOTAL_TO_LOAD == TOTAL_ITEM && TOTAL_ITEM < 1500 && IS_LOADING == false) 
				{
					trace("[Board.updatePos] NEXT");
					IS_LOADING = true
					dispatchEvent(new BoardEvent(BoardEvent.LOADED));
				}
			}
			
			return true
			
		}	
		
		private function setPositions():void 
		{
			var i 		: int= 0;
			var posYL 	: Number = 0
			var posYM 	: Number = 0
			var posYR 	: Number = 0
			var item 	: PhotoItem 
			
			if (Size.getConfig() == Size.SMALL)
			{				
				while (i<TOTAL_ITEM) 
				{
					 item  = items[i] as PhotoItem;
					if (i % 2 == 0)
					{
						item.x = 0
						item.y = posYL
						posYL+=item.H500 + Column.GAPX 
					}
					else
					{
						item.x = Column.WIDTH + Column.GAPX
						item.y = posYR
						posYR+=item.H500 + Column.GAPX 
					}
					i++
				}
			}
			else
			{
				while (i<TOTAL_ITEM) 
				{
					 item  = items[i] as PhotoItem;
					if (i % 3 == 0)
					{
						item.x = 0
						item.y = posYL
						posYL+=item.H500+ Column.GAPX
					}
					else
					{
						if (i % 3 == 1)
						{
							item.x = Column.WIDTH + Column.GAPX;
							item.y = posYM
							posYM += item.H500 + Column.GAPX;
						}
						else
						{
							item.x = Column.WIDTH + Column.GAPX + Column.WIDTH + Column.GAPX;
							item.y = posYR
							posYR += item.H500 + Column.GAPX ;
						}						
					}
					i++
				}
			}
		}
		
		private function createQueue():void 
		{
			var loaderContext:LoaderContext = new LoaderContext();
				// specify async decoding
				//loaderContext.imageDecodingPolicy = ImageDecodingPolicy.ON_LOAD;

			LoaderMax.defaultAuditSize = false
			queue = new LoaderMax({name:"mainQueue" , onChildComplete :onChildComplete, onError:errorHandler , onComplete : onQueueComplete  , noCache : false});
			queue.maxConnections = 3;
			
		}
		
		private function loadItems():void 
		{				
			var i:int = 0;	
			while (i<this.TOTAL_ITEM) 
			{
				var item : PhotoItem = items[i] as PhotoItem;		
				if ( item.isLoaded == false)
				{
					queue.append(  new ImageLoader(item.data.URL500, { name:item.name , noCache : false } ) );				
					trace("[Board.loadItems] append " + item.name);
					IS_LOADING = true
				}	
				i++;
			}						
			
			queue.load();
			dispatchEvent(new BoardEvent(BoardEvent.START_LOADING));			
		}
		
	
		////////////////////////////////////////////////////////////////////
		///////// 				LOADING HANDLERS
		////////////////////////////////////////////////////////////////////
 
		private function onQueueComplete(e:LoaderEvent):void
		{
			trace("[Board.onQueueComplete] "+TOTAL_TO_LOAD , TOTAL_ITEM);			
			IS_LOADING = false
			setMaxY()			
			dispatchEvent(new BoardEvent(BoardEvent.STOP_LOADING));
			
			max_posy = this.height - Main.INSTANCE.stage.stageHeight + 50
			
			
				
		}
		
	
		private function onChildComplete(e:LoaderEvent):void 
		{
			TOTAL_LOADED ++;						
			IS_LOADING = false;
			//trace("[Board.onChildComplete] " + e.target.name);
			addImageToItem(e.target.name);					
			setMaxY()			
			dispatchEvent(new BoardEvent(BoardEvent.STOP_LOADING));
			
			
			
		}
		
		private function errorHandler(event:LoaderEvent):void 
		{
			trace("error occured with " + event.target + ": " + event.text);
		}
		
		private function addImageToItem(p_name:String):void 
		{			
			
			
			
			var image:ContentDisplay = LoaderMax.getContent(p_name);
			var bmData : BitmapData= (image.rawContent as Bitmap ).bitmapData
			canvas.copyPixels(	bmData, new Rectangle(0, 0, 1, 1), zp);		
			var item : PhotoItem = getChildByName(p_name) as PhotoItem;
				item.addImage(image);
		}
		 
		
		
		/////////////////////////////////////////
		//////////////////	GETTERS SETTERS
		 
		private function setMaxY():void 
		{
			var i:int = 0;	
			while (i<TOTAL_ITEM) 
			{
				var item : PhotoItem = items[i] as PhotoItem;				
				if ( item.isLoaded == false && max_posy<height )
				{
					if( item.y + item.height >max_posy)
						max_posy = item.y + item.height;
					i = TOTAL_ITEM;
				}
				i++;
			}			
			
			percent = -  ( this.y ) / ( max_posy  ) ;			
		//	trace("[Board.setMaxY] "+percent , this.y , max_posy );
		}
		
		private function isVisible(item:PhotoItem):Boolean 
		{			
			var visible : Boolean = false			
			var sw : Number = stage.stageWidth + 50 ;			
			var sh : Number = stage.stageHeight  ;			
			if (  ( item.y + this.y ) >=  -800  && ( item.y + this.y ) <= sh + 2  ) visible  = true;
			return visible;
		}			
	
		
	}	
}